import { PlusOutlined, LikeOutlined, MessageOutlined, SettingOutlined, LikeFilled } from '@ant-design/icons';
import { Drawer, Layout, Menu, Dropdown, Avatar, message } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import MdEditor from 'md-editor-rt';
import intl from 'react-intl-universal';
import $ from 'jquery';
import MyComment from './comment';
import { storage } from '../../utils/localstorage';
import 'antd/dist/antd.min.css';
import '../home.css';


const ArticleDetails = () => {
  // 文章
  const [articleData, setArticleData] = useState({
    id: -1,
    author: null,
    kind: null,
    title: '',
    text: '',
    likes: [],
    views: 0,
    comments: [],
  });

  // 获取文章相关数据
  const location = useLocation();
  const [hasChange, setHasChange] = useState(true);
  useEffect(() => {
    const getArticleData = () => {
      $.ajax({
        url: '/home/article/details',
        type: 'post',
        data: {aid: location.pathname.split('/')[2]},
        dataType: 'json',
        success: function(result) {
          if (result.status === 1) {
            // console.log('details', result.data)
            setArticleData({
              id: result.data.aid,
              author: result.data.author,
              kind: result.data.kind,
              title: result.data.title,
              text: result.data.content,
              likes: result.data.likes,
              views: result.data.views,
              comments: result.data.comments,
            });
          } else {
            message.info('内容加载失败，请稍后再试！');
          }
        },
        error: function(err) {
          alert(JSON.stringify(err));
        },
      });
    };
    hasChange && getArticleData();
    setHasChange(false);
  }, [hasChange]);


  // 展示评论
  const [drawerVisible, setDrawerVisible] = useState(false);
  const showDrawer = () => {
    setDrawerVisible(true);
  };
  const closeDrawer = () => {
    setDrawerVisible(false);
  };


  // 退出登录
  const logout = () => {
    window.location.replace('/login');
    storage.remove('user');                                         // 移除用户信息
  };


    // 上面菜单栏
    const menu = (
      <Menu items={[ { key: '3', label: (<span onClick={logout}>退出登录</span>)}]} />
  );


  // 点赞。id即文章id；type即类型，1表示点赞，-1表示取消点赞
  const doLike = (id, type) => {
    let data = {};
    if (type === 1) {
      data = {uid:storage.get('user').uid, aid:id, type:type, pType:3};
    } else {
      data = {uid:storage.get('user').uid, aid:id, type:type, pType:4};
    }
    $.ajax({
      url: '/home/article/like',
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(result) {
        setHasChange(true);
      },
      error: function(err) {
        message.info('网络繁忙，请稍后再试');
      }
    })
  };


  // 渲染组件
  return (
    <Layout>
      <div className="header" style={{backgroundColor:'black'}}>
        <div className="logo" />
        <Avatar className='headerAvatar' style={{ backgroundColor: '#f56a00', verticalAlign: 'middle', }} size="large" gap={4}>U</Avatar>
        <Dropdown overlay={menu} placement="bottomLeft">
          <SettingOutlined className='headerSetting' />
        </Dropdown>
      </div>
      <div style={{width:'1200px', height:'100%', margin:'20px auto'}}>
        <input disabled='disabled' size='large' value={articleData.title} 
          style={{backgroundColor:'#fff', width:'100%', marginBottom:'8px', fontSize:'28px', fontWeight:'bolder', borderColor:'#fff',
          borderStyle:'none', paddingLeft:'20px'}} />
        <MdEditor modelValue={articleData.text} previewOnly style={{marginBottom:'20px', paddingLeft:'10px', paddingRight:'10px'}} />
        <div style={{backgroundColor:'#fff', width:'1200px', height:'60px', display:'flex', alignItems:'center',}}>
            <div style={{paddingLeft:'10px'}}>
              { 
                (articleData.likes.indexOf(storage.get('user').uid) === -1) ? 
                <LikeOutlined className='like' onClick={() => doLike(articleData.id, 1)} style={{width:'24px', height:'24px', fontSize:'18px'}} /> : 
                <LikeFilled className='like' onClick={() => doLike(articleData.id, -1)} style={{color:'red', width:'24px', height:'24px', fontSize:'18px'}} />
              }
              {articleData.likes.length}
            </div>
            <div style={{marginLeft:'20px'}} onClick={showDrawer}>
              <MessageOutlined style={{width:'24px', height:'24px', fontSize:'18px'}} />
              {articleData.comments.length}
            </div>
        </div>
      </div>
      <Drawer title="评论" width={'26%'} onClose={closeDrawer} visible={drawerVisible} bodyStyle={{ paddingBottom: 80, }} 
        destroyOnClose={true}>
        <MyComment closeDrawer={closeDrawer} setHasChange={setHasChange} data={articleData} />
      </Drawer>
    </Layout>
  );
};

export default ArticleDetails;